<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="客户编码" prop="code">
          <CodeRuleInput
            :band-value.sync="formData.code"
            table-name="sale_customer"
            column-name="code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="简称">
          <el-input v-model="formData.abbreviation" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="客户类别">
          <DictSelect
            :band-value.sync="formData.typeCode"
            dict-type="typeCode"
          />
        </el-form-item>
        <!-- <el-form-item label="所属业务员" class="double clickChoose">
          <el-select
            v-model="formData.manId"

            multiple
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in peopleList"
              :key="item.userId"
              :label="item.realName"
              :value="item.userId"
            />
          </el-select>
          <a
            class="clickChoose_button"
            @click.prevent="choosePeople"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item> -->
        <el-form-item label="所属业务员" class=" clickChoose">
          <MultiUserSelect
            ref="MultiUserSelect"
            :parent="this"
            id-key="salesmanId"
            name-key="salesmanRealName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-if="!formData.planCode"
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item v-if="isShow" label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-divider /> -->
        <!-- <div class="formItem_header">税务信息</div>
        <el-form-item label="计税方式">
          <DictSelect
            :band-value.sync="formData.taxTypeCode"
            dict-type="taxTypeCode"
          />
        </el-form-item>
        <el-form-item label="税率%">
          <DictSelect
            :band-value.sync="formData.taxRateCode"
            dict-type="taxRateCode"
          />
        </el-form-item>
        <el-form-item label="结算方式">
          <DictSelect
            :band-value.sync="formData.settlementTypeCode"
            dict-type="settlementTypeCode"
          />
        </el-form-item>
        <el-form-item label="结算币别">
          <DictSelect
            :band-value.sync="formData.settlementCurrencyCode"
            dict-type="settlementCurrencyCode"
          />
        </el-form-item> -->
        <el-divider />
        <div class="formItem_header">联系信息</div>
        <el-form-item label="联系人">
          <el-input v-model="formData.contacts" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="formData.phone" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="联系地址">
          <el-input v-model="formData.address" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formData.email" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="传真">
          <el-input v-model="formData.fax" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="公司网址">
          <el-input v-model="formData.webAddress" placeholder="请输入" clearable />
        </el-form-item>
        <el-divider />
        <div class="formItem_header">开票信息</div>
        <el-form-item label="名称">
          <el-input v-model="formData.accountName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="纳税人识别号">
          <el-input v-model="formData.taxpayerNumber" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="开户行">
          <el-input v-model="formData.accountBank" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="formData.accountNumber" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="formData.invoicePhone" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="formData.invoiceAddress" placeholder="请输入" clearable />
        </el-form-item>
        <!-- <el-form-item label="电子承兑开户行">
          <el-input v-model="formData.electronicTaxBearingBank" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="电子承兑账号">
          <el-input v-model="formData.electronicTaxBearingAccountNumber" placeholder="请输入" clearable />
        </el-form-item> -->
        <!-- <el-divider /> -->
      </el-form>
      <div class="formItem_header">
        客户料号
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addMater">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="deleteMater">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div
        ref="table_container"
        class="table_container draggableTable"
      >
        <el-table
          ref="table2"
          :data="materData"
          stripe
          border
          style="width: 99.9%;"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange2"
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="客户料号" min-width="120" prop="saleCustomerMaterialCode">
            <template slot-scope="scope">
              <el-input v-model="scope.row.saleCustomerMaterialCode" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" prop="materialName" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" prop="materialModel" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100" prop="materialUnitName">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="formItem_header">
        发货信息
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="deleteRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div
        ref="table_container"
        class="table_container draggableTable"
      >
        <el-table
          ref="table"
          :data="listData"
          stripe
          border
          style="width: 99.9%;"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="交货方式" min-width="140" prop="deliveryTypeCode">
            <template slot-scope="scope">
              <DictSelect :band-value.sync="scope.row.deliveryTypeCode" dict-type="deliveryTypeCode" />
            </template>
          </el-table-column>
          <el-table-column label="收货人" min-width="140" prop="consignee">
            <template slot-scope="scope">
              <el-input v-model="scope.row.consignee" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="联系方式" min-width="140" prop="phone">
            <template slot-scope="scope">
              <el-input v-model="scope.row.phone" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="收货地址" min-width="200" prop="deliveryAddress">
            <template slot-scope="scope">
              <el-input v-model="scope.row.deliveryAddress" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="注意事项" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.attentionMatters" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="默认" min-width="80">
            <template slot-scope="scope">
              <el-radio
                v-model="tableDefaultRow"
                :label="scope.$index"
                @change.native="chooseDefault(scope.row,scope.$index)"
              >&nbsp;</el-radio>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import searchMaterial from './searchMaterial.vue'
import { addOrUpdate, getInfo } from '@/api/saleManage/customerInfo'
import { list } from '@/api/system/user'
import seachUser from './seachUser.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    return {
      loading: true,
      isShow: false,
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      defailtSalsesName: '', // 默认所属业务员
      formData: {
        code: '',
        name: '',
        abbreviation: '',
        typeCode: '',
        salesmanId: '',
        salesmanRealName: '',
        // manId: '',
        remark: '',
        status: '1',
        // taxTypeCode: '',
        // taxRateCode: '',
        // settlementTypeCode: '',
        // settlementCurrencyCode: '',
        contacts: '',
        phone: '',
        address: '',
        email: '',
        fax: '',
        webAddress: '',
        accountName: '',
        taxpayerNumber: '',
        accountBank: '',
        accountNumber: '',
        invoicePhone: '',
        invoiceAddress: '',
        // electronicTaxBearingBank: '',
        // electronicTaxBearingAccountNumber: '',
        data: [],
        id: ''
      },
      saveData: [],
      materData: [],
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      selectionsAll2: [], // 表格所有页选中的行
      listData: [],
      tableDefaultRow: '',
      tableData: [],
      peopleList: [],
      rules: {
        code: [
          { required: true, message: '客户编码不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '客户名称不能为空', trigger: 'change' }
        ]

      }
    }
  },
  created() {
    if (!this.id) {
      this.loading = false

      // 设置默认业务员
      this.formData.salesmanId = this.$store.state.user.userId.toString()
      this.formData.salesmanRealName = this.$store.state.user.name
      // console.log()

      // 没有id就是新增
      // Object.keys(this.defaultValue).forEach((key) => {
      //   // 给右边数据赋值
      //   this.formData[key] = this.defaultValue[key]
      // })
    } else {
      this.isShow = true
      // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  mounted() {
    // this.getList()
    this.$refs.MultiUserSelect.setDefaultData()
  },
  methods: {
    headerCellClassName(data) {
      // if (['deliveryTypeCode', 'consignee', 'phone', 'deliveryAddress'].indexOf(data.column.property) != -1) {
      //   return 'column_bt'
      // }
    },
    handleSelectionChange(row) {
      this.selectionsAll = row
    },
    handleSelectionChange2(row) {
      this.selectionsAll2 = row
    },
    getList() {
      list(this.pageData).then(res => {
        this.peopleList = res.data
      })
    },
    peopleChoose(data) {
      this.formData.manId = data.map(item => item.userId)
    },
    addRow() {
      const row = {
        deliveryTypeCode: '',
        consignee: '',
        phone: '',
        deliveryAddress: '',
        attentionMatters: '',
        isDefault: '0'
      }
      if (!this.listData.some(item => item.isDefault == '1')) {
        row.isDefault = '1'
        this.tableDefaultRow = this.listData.length
      }
      this.listData.push(row)
    },
    addMater() {
      if (this.materData && this.materData.length > 0) {
        this.saveData = this.$deepClone(this.materData)
      }
      this.$layer.iframe({
        // 弹框
        content: {
          content: searchMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.materData && this.materData.length > 0 ? this.materData : []
          } // props
        },
        area: ['1320px', '800px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    showMaterial(data2, oldData) {
      // 不能直接替换，如果之前已经添加过，之前填的东西要保留
      const cacheData = []
      data2.forEach((item, index) => {
        if (this.materData && this.materData.some(item2 => item2.materialId == item.materialId)) {
          cacheData.push(this.materData.filter(item2 => item2.materialId == item.materialId)[0])
        } else {
          // item.remark = ''
          item.status = 0
          delete item.id
          cacheData.push(item)
        }
        if (index == data2.length - 1) {
          this.materData = this.$deepClone(cacheData)
        }
      })
      this.materData = cacheData
    },
    deleteRow() {
      this.selectionsAll.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
      // 找到 tableData2 里 isDefault 是 1 的 ，找到它的index
      if (this.listData.filter(item => item.isDefault == 1).length > 0) {
        this.tableDefaultRow = this.listData.indexOf(this.listData.filter(item => item.isDefault == 1)[0])
      } else { // 如果 isDefault 是 1 的 被删除了
        this.tableDefaultRow = 0
      }
      this.$refs.table.clearSelection()
    },
    deleteMater() {
      this.selectionsAll2.forEach(item => {
        this.materData.splice(this.materData.indexOf(item), 1)
      })
      // 找到 tableData2 里 isDefault 是 1 的 ，找到它的index
      if (this.materData.filter(item => item.isDefault == 1).length > 0) {
        this.tableDefaultRow = this.materData.indexOf(this.materData.filter(item => item.isDefault == 1)[0])
      } else { // 如果 isDefault 是 1 的 被删除了
        this.tableDefaultRow = 0
      }
      this.$refs.table2.clearSelection()
    },
    getInfo() {
      getInfo(this.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        console.log(this.formData.salesmanId)
        this.$refs.MultiUserSelect.setDefaultData()
        if (this.formData.salesmanId) {
          var str = this.formData.salesmanId
          var arr = []
          arr = str.split(',')
          this.formData.manId = arr.map(item => Number(item))
        }
        this.listData = this.formData.data
        this.materData = res.data.materialData
        this.isShow = true
        this.loading = false
        this.listData.forEach((ele, index) => {
          if (ele.isDefault == '1') {
            this.tableDefaultRow = index
          }
        })
      })
    },
    chooseDefault(row, currentIndex) {
      console.log(currentIndex)
      this.listData.forEach((ele, index) => {
        console.log(index)
        if (index == currentIndex) {
          ele.isDefault = '1'
        } else {
          ele.isDefault = '0'
        }
        return ele
      })
    },
    choosePeople() {
      const arr = this.formData.salesmanId.split(',')
      arr.forEach(ele => {
        ele = Number(ele)
      })
      this.$layer.iframe({
        // 弹框
        content: {
          content: seachUser, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            userId: arr
          } // props
        },
        area: ['1020px', '650px'],
        title: '选择人员', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 提交
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.listData.filter(item => !item.deliveryTypeCode).length > 0) {
            this.$message.warning('交货方式不能为空')
            return
          }
          // if (this.listData.length <= 0) {
          //   this.$message.warning('请添加发货信息')
          //   return
          // }
          // if (this.listData.filter(item => !item.deliveryTypeCode).length > 0) {
          //   this.$message.warning('交货方式不能为空')
          //   return
          // } else if (this.listData.filter(item => !item.consignee).length > 0) {
          //   this.$message.warning('收货人不能为空')
          //   return
          // } else if (this.listData.filter(item => !item.phone).length > 0) {
          //   this.$message.warning('联系方式不能为空')
          //   return
          // } else if (this.listData.filter(item => !item.deliveryAddress).length > 0) {
          //   this.$message.warning('收货地址不能为空')
          //   return
          // } else {
          if (this.listData.length > 0) {
            if (this.listData.filter(item => item.isDefault == '1').length == 0) {
              this.listData[0].isDefault = '1'
            }
          }
          this.formData.data = this.$deepClone(this.listData)
          this.formData.materialData = this.materData ? this.$deepClone(this.materData) : []
          addOrUpdate(this.formData).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
          // }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    },
    // 获取点检模版数据
    showTemplate(data, name, id, remark) {
      data.forEach((ele) => {
        ele['itemId'] = ele.id
      })
      this.tableData = data
      this.formData.templateId = id
      this.formData.templateName = name
      this.formData.remark = remark
      this.getList()
    },
    // 获取点检设备id
    showEquipment(data) {
      this.formData.bookId = data.id
      this.getList()
    }
    //
  }
}
</script>

<style lang="less" scoped>
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
</style>
